package com.example.jf.jfapp.utils;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

/**
 * 百度定位工具类
 * 定位成功，需要通知调用者，告诉调用者定位成功啦
 * 并且将定位的结果传递给调用者
 *
 * 使用接口回调实现
 */

public class BaiDuLocationUtils {
    private static final String TAG = "BaiDuLocationUtils";
    static OnLocationListener mOnLocationListener;
    private BaiDuLocationUtils(){}
    /**
     * 提供给外界创建对象的方法
     */
    public static void create(Context context, OnLocationListener onLocationListener){
        mOnLocationListener = onLocationListener;
        //初始化定位的参数
        //声明LocationClient类
        LocationClient mLocationClient = new LocationClient(context);
        //注册监听函数
        mLocationClient.registerLocationListener(bdLocationListener);
        LocationClientOption option = new LocationClientOption();

        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);

        //可选，默认gcj02，设置返回的定位结果坐标系
        option.setCoorType("bd09ll");

        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setScanSpan(0);

        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    static BDLocationListener bdLocationListener = new BDLocationListener(){

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if(bdLocation != null) {
                //定位成功
                if (bdLocation.getLocType() == BDLocation.TypeGpsLocation ||
                        bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
//                    //获取定位结果
//                    StringBuffer sb = new StringBuffer(256);
//                    sb.append("\nlatitude : ");
//                    sb.append(bdLocation.getLatitude());    //获取纬度信息
//                    sb.append("\nlontitude : ");
//                    sb.append(bdLocation.getLongitude());    //获取经度信息
//                    Log.e(TAG, "onReceiveLocation: 工具类定位" + sb);
                    if (mOnLocationListener != null) {
                        mOnLocationListener.onLocationSucced(bdLocation, bdLocation.getLatitude(), bdLocation.getLongitude());
                    }
                }
            }
        }
        @Override
        public void onConnectHotSpotMessage(String s, int i) {}
    };

    /**
     * 定位成功的接口回调
     */
    public interface OnLocationListener{
        //定位成功会回调该方法
        void onLocationSucced(BDLocation bdLocation,double latitude, double longitude);

    }
}
